import { toast } from 'sonner';
import { Button } from './ui/button';
import { Task, TaskInfo, TaskType } from '@/entrypoints/hook/useConcurrentRequest';

import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@/components/ui/sheet';
import { ScrollArea, ScrollBar } from './ui/scroll-area';
import { OperationMessage } from '@/store/message';
import {
  Accordion,
  AccordionItem,
  AccordionTrigger,
  AccordionContent,
} from '@radix-ui/react-accordion';

export function BatchCollectOperation({
  activeTask,
  queue,
  completedTask,
  totalTask,
  isStop,
  resume,
  clearQueue,
}: {
  activeTask: React.MutableRefObject<Task[]>;
  queue: React.MutableRefObject<Task[]>;
  completedTask: React.MutableRefObject<Task[]>;
  totalTask: React.MutableRefObject<Task[]>;
  isStop: React.MutableRefObject<boolean>;
  resume: () => void;
  clearQueue: () => void;
}) {
  const [update, setUpdate] = useState({});
  const [sheetOpen, setSheetOpen] = useState(false);

  function displayTasks() {
    setSheetOpen(true);
  }

  function stopBatchCollect() {
    isStop.current = true;
    toast.error('暂停任务,不影响正在执行任务的产品');
  }

  useEffect(() => {
    let timer: number | null = null;
    const href = location.href;
    timer = setInterval(() => {
      // 触发强制渲染
      setUpdate({});
    }, 500) as unknown as number;

    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, []);
  return (
    <div>
      <Sheet open={sheetOpen} onOpenChange={setSheetOpen} modal={false}>
        <SheetContent className="z-[100002] !max-w-[40vw]">
          <SheetHeader>
            <SheetTitle>任务详情</SheetTitle>
          </SheetHeader>
          <ScrollArea className="border pb-4 rounded-sm h-[80vh] w-full p-2 [.group_&]:!absolute [.group_&]:!h-[80vh] [&_[data-radix-scroll-area-viewport]]:!h-[80vh] [&_[data-radix-scroll-area-viewport]]:!overflow-auto">
            <Accordion type="multiple" className="w-full">
              <AccordionItem value="active">
                <AccordionTrigger className="flex items-center gap-2 justify-start py-0 !flex-nowrap">
                  <div className="whitespace-nowrap">
                    正在处理的任务({activeTask.current.length})
                  </div>
                </AccordionTrigger>
                <AccordionContent className="pl-4 whitespace-pre">
                  {JSON.stringify(
                    activeTask.current.map((task) => {
                      const taskInfo = task.task.extraData;
                      return {
                        skuInfo: taskInfo.skuIdInfo,
                        taskType: taskInfo.taskType,
                      };
                    }),
                    null,
                    2,
                  )}
                </AccordionContent>
              </AccordionItem>
              <AccordionItem value="queue">
                <AccordionTrigger className="flex items-center gap-2 justify-start py-0 !flex-nowrap">
                  <div className="whitespace-nowrap">代处理的任务({queue.current.length})</div>
                </AccordionTrigger>
                <AccordionContent className="pl-4 whitespace-pre">
                  {JSON.stringify(
                    queue.current.map((task) => {
                      const taskInfo = task.task.extraData;
                      return {
                        skuInfo: taskInfo.skuIdInfo,
                        taskType: taskInfo.taskType,
                      };
                    }),
                    null,
                    2,
                  )}
                </AccordionContent>
              </AccordionItem>
              <AccordionItem value="completed">
                <AccordionTrigger className="flex items-center gap-2 justify-start py-0 !flex-nowrap">
                  <div className="whitespace-nowrap">
                    已处理的任务({completedTask.current.length})
                  </div>
                </AccordionTrigger>
                <AccordionContent className="pl-4 whitespace-pre">
                  {JSON.stringify(
                    completedTask.current.map((task) => {
                      const taskInfo = task.task.extraData;
                      return {
                        skuInfo: taskInfo.skuIdInfo,
                        taskType: taskInfo.taskType,
                      };
                    }),
                    null,
                    2,
                  )}
                </AccordionContent>
              </AccordionItem>
              <AccordionItem value="total">
                <AccordionTrigger className="flex items-center gap-2 justify-start py-0 !flex-nowrap">
                  <div className="whitespace-nowrap">总的任务({totalTask.current.length})</div>
                </AccordionTrigger>
                <AccordionContent className="pl-4 whitespace-pre">
                  {JSON.stringify(
                    totalTask.current.map((task) => {
                      const taskInfo = task.task.extraData;
                      return {
                        skuInfo: taskInfo.skuIdInfo,
                        taskType: taskInfo.taskType,
                      };
                    }),
                    null,
                    2,
                  )}
                </AccordionContent>
              </AccordionItem>
            </Accordion>
            <ScrollBar orientation="horizontal"></ScrollBar>
          </ScrollArea>
        </SheetContent>
      </Sheet>
      <div className="flex items-center mt-3">
        <Button
          size="sm"
          variant="destructive"
          onClick={resume}
          className="hover:bg-[#337AB7] bg-[#428BCA]"
        >
          恢复批量任务
        </Button>
        <Button
          size="sm"
          variant="destructive"
          onClick={clearQueue}
          className="hover:bg-destructive/90 bg-destructive ml-auto"
        >
          清除任务队列
        </Button>
        <Button
          size="sm"
          variant="destructive"
          onClick={stopBatchCollect}
          className="hover:bg-destructive/90 bg-destructive ml-3"
        >
          暂停批量任务
        </Button>
      </div>
      <div className="mt-2">
        <div className="flex items-center gap-2 cursor-pointer" onClick={displayTasks}>
          <span>批量任务信息:</span>
          <span className="text-[hsl(142.1_76.2%_36.3%)]">{`(正在处理(${activeTask.current.length})`}</span>
          /<span className="text-blue-500">{`待处理(${queue.current.length})`}</span>/
          <span className="text-[hsl(142.1_76.2%_36.3%)]">{`已处理(${completedTask.current.length})`}</span>
          /<span className="text-blue-500">{`总(${totalTask.current.length})`}</span>/
          <span className="text-red-500">{`状态(${isStop.current ? '已暂停' : '运行中'}))`}</span>
        </div>
      </div>
    </div>
  );
}
